<?php
/**
 *  Application middleware
 * @var $app        \Slim\App
 * @var $config     \slimExt\DataCollector
 * @var $container  \slimExt\base\Container
 */

use slimExt\base\Request;
use slimExt\base\Response;

// Slim 处理带有斜线结尾的 URL 和不带斜线的 URL 的方式不同。意思就是 /user 和 /user/ 不是一回事，它们可以有不同的回调。
// redirect '/user/' to '/user'
$app->add(function (Request $request, Response $response, callable $next) {
    $uri = $request->getUri();
    $path = $uri->getPath();
    if ($path !== '/' && substr($path, -1) === '/') {
        // permanently redirect paths with a trailing slash
        // to their non-trailing counterpart
        $uri = $uri->withPath(substr($path, 0, -1));
        return $response->withRedirect((string)$uri, 301);
    }

    return $next($request, $response);
});

// enable Csrf Token
if ( $config->get('enableCsrfToken', true) ) {
    $app->add( $container->get('csrf') );
}

// add debug tool : Whoops
$app->add(new \inhere\whoops\middleware\WhoopsTool($app));
$app->add(\slimExt\middlewares\Prepared::class);
